# -*- coding: utf-8 -*-
# @Time : 2022/5/31 0:36
# @Author : Dftre
# @Email : 3066417822@qq.com
# @File : generatorPlus.py
# @Project : 代码生成器
# @Version : 1.0.1
import os

from generator import Generator
from mysql import MysqlTableMessage


class GeneratorPlus:
    def __init__(self, user, password, database, table: str,  # 数据库基本信息：账号，密码，数据库，表名

                 host="localhost", port=3306, charset='utf8'):  # 数据库常规信息：数据库地址，数据库端口号，数据库编码
        self.table = table
        self.mtm = MysqlTableMessage(
            user=user, password=password, database=database,
            host=host, port=port, charset=charset, table=table
        )
        self.gen = None

    def start(
            self, path, to='.',  # 模板信息：模板名称，模板类型，模板所在路径
            sub_dictionary: dict = None, val_dictionary: dict = None,  # 额外信息：字段模板字典，插值语法字典
            if_list: list[str] = None, ToDo=1
    ):
        template_name = os.path.basename(path)  # Table.vue
        template_type = os.path.splitext(path)[-1]  # .vue
        if to != '.':
            os.makedirs(to)
        self.gen = Generator()
        if sub_dictionary:
            for i in sub_dictionary:
                self.gen.add_val(i, self.mtm.sub(sub_dictionary[i]))
        if val_dictionary:
            self.gen.add_val_dict(val_dictionary)
        if if_list:
            self.gen.add_if_list(if_list)
        java_field_type = {
            'varchar': 'String',
            'bigint': 'Long',
            'int': 'Integer',
            'datetime': 'LocalDateTime',
            'blob': 'Blob',
            'tinyint': 'Boolean',
        }
        if template_type == '.java':
            try:
                for n, i in enumerate(self.mtm.fields):
                    self.mtm.fields[n]['type'] = java_field_type[self.mtm.fields[n]['type']]
            except:
                pass
        for i in self.mtm.fields:
            self.gen.add_class_dict('field', i)
        self.gen.add_val('endl', '\n')
        self.gen.add_val('database', self.table)
        self.gen.add_val('DATABASE', self.table.upper())
        self.gen.add_val('Database', self.table.title())
        with open(path, 'r', encoding='utf8') as f:
            TEXT = ''.join(f.readlines())
        with open((to + '/{}').format(self.table + template_name), 'w', encoding='utf8') as f:
            for i in range(ToDo):
                TEXT = self.gen.start(TEXT)
            f.write(TEXT)


if __name__ == '__main__':
    pass
